/* eslint-disable import/no-anonymous-default-export */
const initState={
    tablist:[],
    shopcar:[]
}
export default (state = initState,action)=>{
    let newState=JSON.parse(JSON.stringify(state))
    if(action.type==='SET_LIST'){
        newState.tablist=action.list
    }else if(action.type==="ADD"){
        let index=newState.shopcar.findIndex(item=>item.id===action.pro.id);
        if(index === -1){
            action.pro.num=1
            newState.shopcar.push(action.pro);
            newState.tablist.forEach(item=>{
                let ind=item.children.findIndex(val=>val.id===action.pro.id)
                if(ind!==-1&&item.children[ind].num>0){
                    item.children[ind].num--
                }
            })
        }else{
            newState.shopcar[index].num++
            newState.tablist.forEach(item=>{
                let ind=item.children.findIndex(val=>val.id===action.pro.id)
                if(ind!==-1&&item.children[ind].num>0){
                    item.children[ind].num--
                }
            })
        }
    }else if(action.type==="ChangeNum"){
        if(action.count==='+'){
            newState.tablist.forEach(item=>{
                let ind=item.children.findIndex(val=>val.id===action.id)
                if(ind!==-1&&item.children[ind].num>0){
                    item.children[ind].num--
                    newState.shopcar.filter(item=>item.id===action.id)[0].num++
                }
            })
        }else if(action.count==='-'){
            newState.shopcar.filter(item=>item.id===action.id)[0].num--
            newState.tablist.forEach(item=>{
                let ind=item.children.findIndex(val=>val.id===action.id)
                if(ind!==-1){
                    item.children[ind].num++
                }
            })
            if(newState.shopcar.filter(item=>item.id===action.id)[0].num<1){
                newState.shopcar.splice(newState.shopcar.findIndex(item=>item.id===action.id),1);
            }
        }
        
    }
    return newState
}